package san.web.dictionary;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import san.entity.dictionary.Dictionary;
import san.service.dictionary.DictionaryService;
import san.service.system.InitAuthorityService;

import com.web.page.Page;
import com.web.struts2.CRUDSupportAction;

@ParentPackage("default")
@Results( { @Result(name = "reload", location = "dictionary.shtml", type = "redirect") })
public class DictionaryAction extends CRUDSupportAction {
	/**
	 * DictionaryAction类.
	 */
	private static final long serialVersionUID = 5255900905150493687L;
	@Autowired
	private DictionaryService dictionaryService;
	private Page<Dictionary> page = new Page<Dictionary>(10);// 每页10条记录
	private Dictionary dictionary;
	@Autowired
	private InitAuthorityService initAuthorityService;

	@Override
	protected void prepareModel() throws Exception {
		if (dictionary != null && StringUtils.isNotBlank(dictionary.getId())) {
			dictionary = dictionaryService.get(dictionary.getId());
		} else {
			if (StringUtils.isNotBlank(getId())) {
				dictionary = dictionaryService.get(getId());
			} else {
				dictionary = new Dictionary();
			}
		}
	}

	@Override
	public String delete() throws Exception {
		if (StringUtils.isNotBlank(getId())) {
			dictionaryService.delete(getId());
		}
		return RELOAD;
	}

	@Override
	public String input() throws Exception {
		return "input";
	}

	@Override
	public String list() throws Exception {
		dictionary = dictionaryService.getDictionaryRoot();
		if (dictionary == null) {
			dictionary = new Dictionary();
			dictionary.setName("abcd");
		}
		return SUCCESS;
	}

	@SuppressWarnings("finally")
	@Override
	public String save() throws Exception {
		try {
			dictionaryService.save(dictionary);
			addActionMessage("保存成功!");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError("保存失败!");
		} finally {
			return RELOAD;
		}
	}

	/*
	 * 初始化权限，暂时放在这里
	 */
	public String initAuthority() throws Exception {
		initAuthorityService.initAll();
		return RELOAD;
	}

	public Page<Dictionary> getPage() {
		return page;
	}

	public void setPage(Page<Dictionary> page) {
		this.page = page;
	}

	public Dictionary getDictionary() {
		return dictionary;
	}

	public void setDictionary(Dictionary dictionary) {
		this.dictionary = dictionary;
	}

}
